package com.ops.uitl.jdbc;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import org.apache.log4j.Logger;

public class SimpleStatement implements IStatement {
	
	private final Logger log = Logger.getLogger(this.getClass());
	
	private Statement statement;
	private String sql;
	private String[] sqls;
	
	/**
	 * construct function
	 * @param conn
	 * @param sqlstr
	 * @throws Exception
	 */
	public SimpleStatement(Connection conn, String sqlstr) throws Exception {
		statement = conn.createStatement();
		this.sql = sqlstr;
	}
	
	/**
	 * construct function
	 * @param conn
	 * @param sqlsstr
	 * @throws Exception
	 */
	public SimpleStatement(Connection conn, String[] sqlsstr) throws Exception {
		statement = conn.createStatement();
		this.sqls = sqlsstr;
	}
		
	/**
	 * get sql
	 * @return String
	 * @throws Exception
	 */
    public String getSql() throws Exception {
    	return sql;
    }

	/**
	 * get statement
	 * @return Statement
	 * @throws Exception
	 */
    public Statement getStatement() throws Exception {
    	return statement;
    }

	/**
	 * execute query
	 * @return ResultSet
	 * @throws Exception
	 */
    public ResultSet executeQuery() throws Exception {
    	if (log.isDebugEnabled()) log.debug("SQL " + sql);
    	
    	try {
    		long beginTime = System.currentTimeMillis();
    		ResultSet result = statement.executeQuery(sql);
    		DaoHelper.getExecuteTimeBySql(log, beginTime);
    		return result;
    	} catch (java.sql.SQLException e) {
    		log.error("ERROR SQL " + sql);
    		throw e;
    	}
    }
    
    /**
     * execute update
     * @return int
     * @throws Exception
     */
    public int executeUpdate() throws Exception {
    	if (log.isDebugEnabled()) log.debug("SQL " + sql);
    	
    	try {
    		long beginTime = System.currentTimeMillis();
    		int result = statement.executeUpdate(sql);
    		DaoHelper.getExecuteTimeBySql(log, beginTime);
    		return result;
    	} catch (java.sql.SQLException e) {
    		log.error("ERROR SQL " + sql);
    		throw e;
    	}
    }
    
    /**
     * execute batch
     * @return int[]
     * @throws Exception
     */
    public int[] executeBatch() throws Exception {
    	for (int i=0; i<sqls.length; i++) {
    		if (log.isDebugEnabled()) log.debug("SQL " + sqls[i]);
    		statement.addBatch(sqls[i]);
    	}
    	
    	long beginTime = System.currentTimeMillis();
    	int[] result = statement.executeBatch();
    	DaoHelper.getExecuteTimeBySql(log, beginTime);
    	return result;
    }

	/**
	 * close statement
	 * @throws Exception
	 */
	public void close() throws Exception {
		statement.close();
	}
	
}